/**
 * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.sample.library.portlet.util;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.ResourceBundle;

import com.liferay.portal.kernel.util.CalendarFactoryUtil;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.xml.Document;
import com.liferay.portal.kernel.xml.Element;
import com.liferay.portal.kernel.xml.SAXReaderUtil;

/**
 * <a href="DAOParamUtil.java.html"><b><i>View Source</i></b></a>
 *
 * @author Brian Wing Shun Chan
 *
 */
public class ASUtil {

	// Servlet Request
	public ASUtil() {
	}

	public static final ResourceBundle getResourceBundle() {
		ResourceBundle labels = ResourceBundle.getBundle(Constant.DEFAULT_RESOURCEBUNDER, Locale.ENGLISH);
		return labels;
	}
	
	public static String XMLLanguagueToString(String str) {
		Document contentDoc = null;
		
		if (Validator.isNotNull(str)) {
			try {
				contentDoc = SAXReaderUtil.read(str);
				str = contentDoc.getRootElement().element("static-content").getTextTrim();
			}
			catch (Exception e) {
				contentDoc = null;
				return null;
			}
		}
		return str;
	}
	public static String[] XMLLanguagueToAvaiableLocales(String str) {
		Document contentDoc = null;
		
		String[] availableLocales = null;
		
		if (Validator.isNotNull(str)) {
			try {
				contentDoc = SAXReaderUtil.read(str);
				Element contentEl = contentDoc.getRootElement();
				availableLocales = StringUtil.split(contentEl.attributeValue("available-locales"));
			}
			catch (Exception e) {
				contentDoc = null;
				return null;
			}
		}
		return availableLocales;
	}
	
	public static final long getMinDate() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(1754, 1, 1);
		return calendar.getTimeInMillis();
	}

	public static final long getMaxDate() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(9999, 1, 1);
		return calendar.getTimeInMillis();
	}

	public static final DecimalFormat getNumFormat() 
	{
		NumberFormat numFormatter = NumberFormat.getNumberInstance(Constant.DEFAULT_LOCAL);
		DecimalFormat decFormatter = (DecimalFormat)numFormatter;
		decFormatter.applyPattern("#0.0");
		return decFormatter;
	}
	
    public static int getDiff( java.util.Date pFrom, java.util.Date pTo )
    {
        int lMultiplier = 1;
        if ( pFrom.after( pTo ) );
        {
            lMultiplier = -1;
            java.util.Date pTemp = pTo;
            pTo = pFrom;
            pFrom = pTemp;
        }
 
        Calendar lFrom = new GregorianCalendar();
        lFrom.setTime( pFrom );
        Calendar lTo = new GregorianCalendar();
        lTo.setTime( pTo );
 
        int lFromYear = lFrom.get( Calendar.YEAR );
        int lFromMonth = lFrom.get( Calendar.MONTH );
        int lFromDay = lFrom.get( Calendar.DAY_OF_MONTH );
 
        int lToYear = lTo.get( Calendar.YEAR );
        int lToMonth = lTo.get( Calendar.MONTH );
        int lToDay = lTo.get( Calendar.DAY_OF_MONTH );
 
        int lYearDiff = lToYear - lFromYear;
        int lMonthDiff = lToMonth - lFromMonth;
        int lDayDiff = lToDay - lFromDay;
 
        if ( lDayDiff < 0 )
        {
            lMonthDiff--;
            Calendar lTemp = new GregorianCalendar();
            lTemp.setTime( pTo );
            lTemp.add( lTemp.MONTH, -1 );
            lDayDiff = lTemp.getActualMaximum( lTemp.DAY_OF_MONTH ) + lDayDiff;
        }
 
        if ( lMonthDiff < 0 )
        {
            lYearDiff--;
            lMonthDiff = 12 + lMonthDiff;
        }
 
        return lMultiplier * ( lYearDiff * 10000 + lMonthDiff * 100 + lDayDiff );
    }

    public static int getYearDifference(Calendar fromCalendar, Calendar toCalendar) {
    	int count = 0;
    	for(fromCalendar.add(Calendar.YEAR, 1); fromCalendar.compareTo(toCalendar) <= 0; fromCalendar.add(Calendar.YEAR, 1)) {
    		count++;
    	}
    	return count;
    }

   	public static int getMonthDifference(Calendar fromCalendar, Calendar toCalendar) {
    	int count = 0;
    	for(fromCalendar.add(Calendar.MONTH, 1); fromCalendar.compareTo(toCalendar) <= 0; fromCalendar.add(
    	Calendar.MONTH, 1)) {
    		count++;
    	}
    	return count;
    }

    public static int getDateDifference(Calendar fromCalendar, Calendar toCalendar) {
    	long diff = toCalendar.getTimeInMillis() - fromCalendar.getTimeInMillis();
    	return (int) (diff / (1000 * 60 * 60 * 24) + 1);
    }


    public static Calendar getEndDateByNumOfmonths(Calendar beginDate, Double numOfMonths) {
	    int numOfMonthsInt = (int) Math.floor(numOfMonths.doubleValue());
	    double decimalPart = numOfMonths.doubleValue() - (double)numOfMonthsInt;
	    // Tinh so thang le
	    if(decimalPart > 0 )	{
	    	beginDate.add(Calendar.MONTH, numOfMonthsInt);
		    // Tinh so ngay le
		    int numOfdays = (int) Math.floor(decimalPart * Constant.NUM_DAYS_PER_MONTH);
		    beginDate.add(Calendar.DATE, numOfdays);
	    }
	    else	{
	    	beginDate.add(Calendar.MONTH, numOfMonthsInt);
	    }
	    beginDate.add(Calendar.DAY_OF_MONTH, -1);
	    return beginDate;
    }
    
    public static boolean IsTimeOverlap(Date begin, Date end, Date beginNew, Date endNew) {
    	Calendar beginCal = CalendarFactoryUtil.getCalendar();
    	beginCal.setTime(begin);
       	Calendar endCal = CalendarFactoryUtil.getCalendar();
    	endCal.setTime(end);
    	
       	Calendar beginNewCal = CalendarFactoryUtil.getCalendar();
    	beginNewCal.setTime(beginNew);
       	Calendar endNewCal = CalendarFactoryUtil.getCalendar();
       	
    	endNewCal.setTime(endNew);
    	if(beginNewCal.after(endCal))
    		return false;
		return true;
    	
    }
    
    public static Date getBeginDateByMonth(int month, int year) {
    	Calendar calBegin = CalendarFactoryUtil.getCalendar();
    	calBegin.set(Calendar.MONTH, month);
    	calBegin.set(Calendar.DATE, 1);
    	calBegin.set(Calendar.YEAR, year);
    	calBegin.set(Calendar.HOUR, 0);
    	calBegin.set(Calendar.MINUTE, 0);
    	calBegin.set(Calendar.SECOND, 0);
    	return calBegin.getTime();
    }

    public static Date getEndDateByMonth(int month, int year) {
    	Calendar calEnd = CalendarFactoryUtil.getCalendar();
    	calEnd.set(Calendar.MONTH, month);
    	calEnd.set(Calendar.DATE, 1);
    	calEnd.set(Calendar.YEAR, year);
    	int lastDate = calEnd.getActualMaximum(Calendar.DATE);
    	calEnd.set(Calendar.DATE, lastDate);
    	calEnd.set(Calendar.HOUR_OF_DAY, 23);
    	calEnd.set(Calendar.MINUTE, 59);
    	calEnd.set(Calendar.SECOND, 59);
    	return calEnd.getTime();
    }
    
    public static Date getBeginDateByQuater(int quater, int year) {
    	int month = (quater - 1)*3;
    	Calendar calBegin = CalendarFactoryUtil.getCalendar();
    	calBegin.set(Calendar.MONTH, month);
    	calBegin.set(Calendar.DATE, 1);
    	calBegin.set(Calendar.YEAR, year);
    	calBegin.set(Calendar.HOUR, 0);
    	calBegin.set(Calendar.MINUTE, 0);
    	calBegin.set(Calendar.SECOND, 0);
    	return calBegin.getTime();
    }
    public static Date getEndDateByQuater(int quater, int year) {
    	int month = quater*3;
    	Calendar calEnd = CalendarFactoryUtil.getCalendar();
    	calEnd.set(Calendar.MONTH, month-1);
    	int maxDay = calEnd.getActualMaximum(Calendar.DAY_OF_MONTH);
    	calEnd.set(Calendar.DATE, maxDay);
    	calEnd.set(Calendar.YEAR, year);
    	calEnd.set(Calendar.HOUR_OF_DAY, 23);
    	calEnd.set(Calendar.MINUTE, 59);
    	calEnd.set(Calendar.SECOND, 59);
    	return calEnd.getTime();
    }

    public static Date getBeginDateByHaftYear(int haftYear, int year) {
    	int month = (haftYear - 1)*6;
    	Calendar calBegin = CalendarFactoryUtil.getCalendar();
    	calBegin.set(Calendar.MONTH, month);
    	calBegin.set(Calendar.DATE, 1);
    	calBegin.set(Calendar.YEAR, year);
    	calBegin.set(Calendar.HOUR, 0);
    	calBegin.set(Calendar.MINUTE, 0);
    	calBegin.set(Calendar.SECOND, 0);
    	return calBegin.getTime();
    }

    public static Date getEndDateByHaftYear(int haftYear, int year) {
    	int month = haftYear*6;
    	Calendar calEnd = CalendarFactoryUtil.getCalendar();
    	calEnd.set(Calendar.MONTH, month-1);
    	int maxDay = calEnd.getActualMaximum(Calendar.DAY_OF_MONTH);
    	calEnd.set(Calendar.DATE, maxDay);
    	calEnd.set(Calendar.YEAR, year);
    	calEnd.set(Calendar.HOUR_OF_DAY, 23);
    	calEnd.set(Calendar.MINUTE, 59);
    	calEnd.set(Calendar.SECOND, 59);
    	return calEnd.getTime();
    }
    public static Date getBeginDateByYear(int year) {
    	Calendar calBegin = CalendarFactoryUtil.getCalendar();
    	calBegin.set(Calendar.MONTH, Calendar.JANUARY);
    	calBegin.set(Calendar.DATE, 1);
    	calBegin.set(Calendar.YEAR, year);
    	calBegin.set(Calendar.HOUR, 0);
    	calBegin.set(Calendar.MINUTE, 0);
    	calBegin.set(Calendar.SECOND, 0);
    	return calBegin.getTime();
    }

    public static Date getEndDateByYear(int year) {
    	Calendar calEnd = CalendarFactoryUtil.getCalendar();
    	calEnd.set(Calendar.MONTH, Calendar.DECEMBER);
    	calEnd.set(Calendar.DATE, 31);
    	calEnd.set(Calendar.YEAR, year);
    	calEnd.set(Calendar.HOUR_OF_DAY, 23);
    	calEnd.set(Calendar.MINUTE, 59);
    	calEnd.set(Calendar.SECOND, 59);
    	return calEnd.getTime();
    }

    public static Date convertYYYYmmDDHHMMssToDate(String strDate){
		int year = Integer.parseInt(strDate.substring(0,4));
		int month = Integer.parseInt(strDate.substring(4,6));
		int day = Integer.parseInt(strDate.substring(6,8));
		int hour = Integer.parseInt(strDate.substring(8,10));
		int minute = Integer.parseInt(strDate.substring(10,12));
		int sec = Integer.parseInt(strDate.substring(12,14));
		int amPm = Calendar.PM;

		if ((month >= 0) && (day > 0) && (year > 0)) {
			Calendar cal = CalendarFactoryUtil.getCalendar();
			cal.set(year, month-1, day, hour, minute, sec);
			return cal.getTime();
		}
		else {
			return null;
		}			
    }
    
    public static String convertYYYYmmDDHHMMssToString(String strYYYYmmDDHHMMss){
    	String year = strYYYYmmDDHHMMss.substring(0, 4);
    	String mm = strYYYYmmDDHHMMss.substring(4, 6);
    	String dd = strYYYYmmDDHHMMss.substring(6, 8);
    	return dd + "/"+mm+"/"+year;
    }
    
    public static String convertDateToYYYYmmDD(Date date){
    	if( date != null) {
    		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
    		return format.format(date) + "000000";
    	}
    	return null;
    }
    
    public static String capitalizeString(String string) {
		string = string.trim();
		char[] chars = string.toLowerCase().toCharArray();
		boolean found = false;
		for (int i = 0; i < chars.length; i++) {
			if (!found && Character.isLetter(chars[i])) {
				chars[i] = Character.toUpperCase(chars[i]);
				found = true;
			} else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
				found = false;
		    }
		  }
		return String.valueOf(chars);
	}
    
    
}